import { ListOption, APIBase } from '../../base/api-base';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class WhitelistService implements Resolve<any> {
  constructor(private http: HttpClient) {}

  async resolve(route: ActivatedRouteSnapshot) {
    const page = Number(route.queryParamMap.get('page')) || 1;
    const count = Number(route.queryParamMap.get('count')) || 10;
    const options: ListOption = { page, count };
    return this.whitelist<WhiteList>(route, options);
  }

  async modifyAuth(payload) {
    return await this.http.patch(`/api/admin/usb/auth`, { 
      auth_type: payload.auth_type,
      whitelist_id: payload.whitelist_id,
      pc_id: payload.pc_id
    }).toPromise();
  }

  async update(whitelistId: number, payload: WhitelistOptions) {
    return await this.http.put(`/api/admin/usb/whitelist/${whitelistId}`, payload).toPromise();
  }

  // 添加白名单
  addWhitelist(id:number, data: WhiteList) {
    console.log('data', data);
    return this.http.post(`/api/admin/usb/whitelist/${id}`, data).toPromise();
  }

  // 移出白名单
  removeWhitelist(id: number) {
    return this.http.delete(`/api/admin/usb/whitelist/${id}`).toPromise();
  }

  whitelist<T>(route: ActivatedRouteSnapshot, options: WhitelistOptions) {
    this.parseUsbParams(route, options);
    let base = new APIBase<any, T>(this.http, '/api/admin/usb/white/list');
    return base.list(options);
  }

  whitelistDetail(id: number) {
    return this.http.get<WhiteList>(`/api/admin/usb/whitelist/${id}`).toPromise();
  }

  parseUsbParams(route: ActivatedRouteSnapshot, options: ListOption) {
    let keys: string[] = ['area_id', 'keywords'];
    this.doParseParams(route, options, keys);
  }

  doParseParams(route: ActivatedRouteSnapshot, options: ListOption, keys: string[]) {
    for (let k of keys) {
      let v = route.queryParamMap.get(k);
      if (v) {
        (options as any)[k] = v;
      }
    }
  }
}

export interface WhiteList {
  id?: number,
  alias_name?: string,
  remarks?: string,
  vendor_id?: string,
  product_id?: string,
  serial_number?: string,
  expiry_date?: string,
  created_at?: string,
  updated_at?: string,
  authorization?: number
  remaining_date?: string
}

export interface WhitelistOptions extends ListOption {
  id?: number;
  auth_type?: number;
  keywords?: string;
  area_id?: number;
  is_authorized?: number;
}